import 'package:flutter/material.dart';

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("1. 通过RenderObject自绘组件"),
        Text("在performLayout方法中，我们设置了组件的大小为直径的两倍，然后在paint方法中绘制了一个圆形"),
        CustomCircle(color: Colors.red, radius: 36),
        SizedBox(height: 30),
        Text("2. Q: 搞了半天，RenderObject的本质还是painter，那为什么不直接用CustomPainter呢?"),
        Text(
            "A1: 因为CustomPainter只能绘制静态的图形，不能实现动画效果?。而RenderObject可以实现动画效果，并且可以自定义绘制逻辑。"),
        Text(
            "A2: 需要更复杂的自定义布局、交互和动画时，RenderObject是更合适的选择。而对于简单的自定义绘制，使用CustomPainter更加方便")
      ],
    );
  }
}

class CustomCircle extends LeafRenderObjectWidget {
  final Color color;
  final double radius;

  CustomCircle({
    required this.color,
    required this.radius,
  });

  @override
  RenderObject createRenderObject(BuildContext context) {
    return RenderCustomCircle(color: color, radius: radius);
  }
}

class RenderCustomCircle extends RenderBox {
  Color color;
  double radius;

  RenderCustomCircle({
    required this.color,
    required this.radius,
  });

  @override
  void paint(PaintingContext context, Offset offset) {
    final Paint paint = Paint()..color = color;
    final Offset circleOffset = offset + Offset(radius, radius);
    context.canvas.drawCircle(circleOffset, radius, paint);
  }

  @override
  // 设置组件大小
  void performLayout() {
    size = Size(radius * 2, radius * 2);
  }
}

void main(List<String> args) {
  runApp(MaterialApp(
    home: Scaffold(body: Demo()),
  ));
}
